package Service;

import Dao.*;
import Dao.Impl.FinancialProductDAOImpl;
import Dao.Impl.TransactionDAOImpl;
import Dao.Impl.UserDAOImpl;
import Model.FinancialProduct;
import Model.Transaction;
import Model.User;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;

import Util.DbConnector;
import Util.EmailSender;
import Util.ReportGenerator;
import Util.Utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class AdminSystem {
    private static final Logger logger = LogManager.getLogger(AdminSystem.class);
    private final ReportGenerator reportGenerator;
    private final UserDAO userDAO;
    private final TransactionDAO transactionDAO;
    private final FinancialProductDAO financialProductDAO;
    private final Scanner scanner;
    Utils utils = new Utils();

    public AdminSystem() {
        this.reportGenerator = new ReportGenerator();
        this.userDAO = new UserDAOImpl();
        this.transactionDAO = new TransactionDAOImpl();
        this.financialProductDAO = new FinancialProductDAOImpl();
        this.scanner = new Scanner(System.in);
    }

    public void adminOperations() {
        boolean loggedIn = true;

        while (loggedIn) {
            System.out.println("=========================");
            System.out.println("欢迎进入管理员模式！");
            System.out.println("主菜单>管理员操作菜单");
            System.out.println("1. 查看所有用户信息");
            System.out.println("2. 删除用户账户");
            System.out.println("3. 查询用户交易信息");
            System.out.println("4. 冻结/解冻用户账户");
            System.out.println("5. 理财产品管理");
            System.out.println("6. 导出用户数据为excel文件");
            System.out.println("0. 退出管理员模式");
            System.out.println("=========================");
            System.out.print("请选择操作(0-6): ");

            int input = utils.getValidMenuChoice(6);

            switch (input) {
                case 1:
                    getAllUser();
                    break;
                case 2:
                    deleteUser();
                    break;
                case 3:
                    getUserTransactionsByUsername();
                    break;
                case 4:
                    toggleUserStatus();
                    break;
                case 5:
                    financialProductManagement();
                    break;
                case 6:
                    reportGenerator.generateUserDataReport();
                    break;
                case 0:
                    System.out.println("已退出管理员模式。");
                    loggedIn = false;
                    break;
                default:
                    System.out.println("无效的选择，请重新输入。");
                    break;
            }
        }
    }

    public void financialProductManagement() {
        boolean running = true;

        while (running) {
            System.out.println("=========================");
            System.out.println("主菜单>管理员操作菜单>理财产品菜单");
            System.out.println("1. 显示理财产品列表");
            System.out.println("2. 添加理财产品");
            System.out.println("3. 修改理财产品");
            System.out.println("4. 上架/下架理财产品");
            System.out.println("5. 删除理财产品");
            System.out.println("6. 发送理财产品推广广告(所有用户)");
            System.out.println("0. 返回上级菜单");
            System.out.println("=========================");
            System.out.print("请选择操作(0-6): ");


            int input = utils.getValidMenuChoice(6);

            switch (input) {
                case 1:
                    // 显示理财产品列表
                    showFinancialProducts();
                    break;
                case 2:
                    addFinancialProduct();
                    break;
                case 3:
                    updateFinancialProduct();
                    break;
                case 4:
                    toggleFinancialProductStatus();
                    break;
                case 5:
                    deleteFinancialProduct();
                    break;
                case 6:
                    sendPromotionAdvertisement();
                    break;
                case 0:
                    running = false;
                    break;
                default:
                    System.out.println("无效的选择，请重新输入。");
                    break;
            }
        }
    }

    private void sendPromotionAdvertisement() {
        System.out.println("正在发送推广广告...");
        try {
            String subject = "💰 稳健理财，财富增值！ 💰";

            // 获取所有理财产品
            List<FinancialProduct> products = financialProductDAO.getAllFinancialProducts();

            // 获取所有用户信息
            User[] users = userDAO.getAllUser();

            // 遍历所有用户，发送邮件
            int successCount = 0; // 发送成功的邮件数量
            int emptyEmailCount = 0; // 邮箱为空的用户的数量

            for (User user : users) {
                String email = user.getContactInfo(); // 获取用户的邮箱地址
                String username = user.getUsername(); // 获取用户的用户名

                if (email != null && !email.trim().isEmpty()) { // 跳过邮箱为空的用户
                    // 生成邮件正文（动态插入用户名）
                    StringBuilder body = new StringBuilder();
                    body.append("亲爱的 ").append(username).append("，\n\n"); // 插入用户名
                    body.append("你是否在寻找一种安全、稳健的理财方式，让你的财富稳步增长？我们为你精心准备了多款理财产品，助你实现财富增值的目标！\n\n");

                    // 添加产品亮点
                    body.append("**产品亮点**\n");
                    body.append("- **高收益**：年化利率高达 ").append(products.get(0).getInterestRate()).append("%，让你的资金快速增值！\n");
                    body.append("- **灵活投资**：最低投资金额灵活，适合不同资金需求的用户。\n");
                    body.append("- **安全保障**：所有理财产品经过严格审核，确保资金安全。\n");
                    body.append("- **随时查看收益**：通过我们的平台，你可以随时查看投资收益，掌握财富动态。\n\n");

                    // 添加推荐产品
                    body.append("**推荐产品**\n");
                    for (FinancialProduct product : products) {
                        if (product.getIsActive()) { // 只展示上架的产品
                            body.append("🌟 **").append(product.getName()).append("** 🌟\n");
                            body.append("- **产品名称**：").append(product.getName()).append("\n");
                            body.append("- **年化利率**：").append(product.getInterestRate()).append("%\n");
                            body.append("- **产品描述**：").append(product.getDescription()).append("\n\n");
                        }
                    }

                    // 添加如何购买
                    body.append("**如何购买**\n");
                    body.append("1. 登录你的账户。\n");
                    body.append("2. 进入“理财产品”页面，选择你感兴趣的产品。\n");
                    body.append("3. 输入购买金额，确认购买。\n");
                    body.append("4. 坐享收益，财富增值！\n\n");

                    // 添加用户评价
                    body.append("**用户评价**\n");
                    body.append("> \"这款理财产品真的太棒了！收益稳定，操作简单，强烈推荐！\"\n");
                    body.append("> \"我一直在寻找安全的理财方式，这款产品完全符合我的需求，收益也很可观！\"\n\n");

                    // 添加立即行动
                    body.append("**立即行动**\n");
                    body.append("现在就登录你的账户，选择适合你的理财产品，开启财富增值之旅吧！\n\n");

                    // 添加广告结尾
                    body.append("📞 **联系我们**：[15629000236] 如有任何疑问，请联系我们的客服团队。\n");
                    body.append("🌐 **官网地址**：[https://www.baidu.com/]\n");
                    body.append("📧 **邮箱**：[1239508231@qq.com]\n");

                    try {
                        EmailSender.sendEmail(email, subject, body.toString());
                        successCount++; // 发送成功，计数器加1
                        logger.info("已向用户 {} 发送推广邮件", username);
                    } catch (Exception e) {
                        logger.error("向用户 {} 发送邮件失败", username, e);
                    }
                } else {
                    emptyEmailCount++; // 邮箱为空，计数器加1
                    logger.warn("用户 {} 的邮箱为空，跳过发送", username);
                }
            }

            // 打印统计结果
            System.out.println("推广广告发送完成！");
            System.out.println("发送成功的邮件数量：" + successCount);
            System.out.println("邮箱为空的用户的数量：" + emptyEmailCount);

        } catch (SQLException e) {
            logger.error("发送促销广告邮件时发生数据库错误", e);
        }
    }

    public void showFinancialProducts() {
        try {
            List<FinancialProduct> products = financialProductDAO.getAllFinancialProducts();
            if (products.isEmpty()) {
                System.out.println("还没有保存的理财产品。");
            } else {
                System.out.println("+-----------------+----------------------+----------------------+----------------------+");
                System.out.printf("| %-15s | %-20s | %-20s | %-20s |\n", "产品ID", "产品名称", "年化利率(%)", "状态");
                System.out.println("+-----------------+----------------------+----------------------+----------------------+");
                for (FinancialProduct product : products) {
                    System.out.printf("| %-15d | %-20s | %-20.2f | %-20s |\n",
                            product.getId(),
                            product.getName(),
                            product.getInterestRate(),
                            product.getIsActive() ? "已上架" : "已下架");
                    System.out.println("产品描述: " + product.getDescription());
                    System.out.println("+-----------------+----------------------+----------------------+----------------------+");
                }
            }
        } catch (SQLException e) {
            logger.error("获取理财产品列表时出错: {}", e.getMessage());
        }
    }

    public void deleteFinancialProduct() {
        try {
            System.out.print("请输入要删除的理财产品ID: ");
            int productId = scanner.nextInt();
            scanner.nextLine(); // 清除输入缓冲区

            FinancialProduct product = financialProductDAO.getFinancialProductById(productId);
            if (product == null) {
                System.out.println("理财产品不存在。");
                return;
            }

            // 确认删除
            System.out.print("确认删除理财产品 '" + product.getName() + "' 吗？(y/n): ");
            String confirm = scanner.nextLine().trim().toLowerCase();
            if (confirm.equals("y")) {
                financialProductDAO.deleteFinancialProduct(productId);
                System.out.println("理财产品已成功删除。");
            } else {
                System.out.println("取消删除操作。");
            }
        } catch (SQLException e) {
            logger.error("删除理财产品时出错: {}", e.getMessage());
        }
    }

    public void toggleFinancialProductStatus() {
        try {
            System.out.print("请输入要修改状态的理财产品ID: ");
            int productId;
            try {
                productId = scanner.nextInt();
                scanner.nextLine(); // 消耗换行符
            } catch (InputMismatchException e) {
                System.out.println("输入无效，请输入一个有效的整数。");
                scanner.nextLine(); // 清除输入缓冲区
                return;
            }

            if (productId <= 0) {
                System.out.println("请输入正确的理财产品ID");
                return;
            }

            FinancialProduct product = financialProductDAO.getFinancialProductById(productId);
            if (product == null) {
                System.out.println("理财产品不存在。");
                return;
            }

            // 显示当前状态并确认更改
            String currentStatus = product.getIsActive() ? "上架" : "下架";
            String newStatus = product.getIsActive() ? "下架" : "上架";

            System.out.print("理财产品 '" + product.getName() + "' 当前状态为" + currentStatus +
                    "，确认" + newStatus + "吗？(y/n): ");
            String confirm = scanner.nextLine().trim().toLowerCase();
            if (confirm.equals("y")) {
                product.setIsActive(!product.getIsActive());
                financialProductDAO.updateFinancialProduct(product);
                System.out.println("理财产品状态已更新为" + newStatus + "。");
            } else {
                System.out.println("取消状态修改操作。");
            }
        } catch (SQLException e) {
            logger.error("修改理财产品状态时出错: {}", e.getMessage());
        }
    }

    public void updateFinancialProduct() {
        try {
            System.out.print("请输入要修改的理财产品ID: ");
            int productId;
            try {
                productId = scanner.nextInt();
                scanner.nextLine(); // 消耗换行符
            } catch (InputMismatchException e) {
                System.out.println("输入无效，请输入一个有效的整数。");
                scanner.nextLine(); // 清除输入缓冲区
                return;
            }

            if (productId <= 0) {
                System.out.println("请输入正确的理财产品ID");
                return;
            }

            FinancialProduct product = financialProductDAO.getFinancialProductById(productId);
            if (product == null) {
                System.out.println("理财产品不存在。");
                return;
            }

            System.out.print("请输入新的理财产品名称: ");
            String name = scanner.nextLine().trim();
            while (name.isEmpty()) {
                System.out.print("名称不能为空，请重新输入: ");
                name = scanner.nextLine().trim();
            }

            System.out.print("请输入新的理财产品描述: ");
            String description = scanner.nextLine().trim();

            System.out.print("请输入新的年化利率: ");
            double interestRate = scanner.nextDouble();
            scanner.nextLine(); // 清除输入缓冲区

            product.setName(name);
            product.setDescription(description);
            product.setInterestRate(interestRate);

            financialProductDAO.updateFinancialProduct(product);
            System.out.println("理财产品修改成功!");
        } catch (SQLException e) {
            logger.error("修改理财产品时出错: {}", e.getMessage());
        }
    }

    public void addFinancialProduct() {
        try {
            System.out.print("请输入理财产品名称: ");
            String name = scanner.nextLine().trim();
            while (name.isEmpty()) {
                System.out.print("名称不能为空，请重新输入: ");
                name = scanner.nextLine().trim();
            }

            System.out.print("请输入理财产品描述: ");
            String description = scanner.nextLine().trim();

            System.out.print("请输入年化利率: ");
            double interestRate = scanner.nextDouble();
            scanner.nextLine(); // 清除输入缓冲区

            FinancialProduct product = new FinancialProduct();
            product.setName(name);
            product.setDescription(description);
            product.setInterestRate(interestRate);
            product.setIsActive(true);

            financialProductDAO.addFinancialProduct(product);
            System.out.println("理财产品添加成功!");
        } catch (SQLException e) {
            logger.error("添加理财产品时出错: {}", e.getMessage());
        }
    }

    public void toggleUserStatus() {
        try {
            System.out.print("请输入要冻结/解冻的用户名: ");
            String name = scanner.nextLine().trim();
            while (name.isEmpty()) {
                System.out.print("用户名不能为空，请重新输入: ");
                name = scanner.nextLine().trim();
            }

            User user = userDAO.getUsrByName(name);

            if (user == null) {
                System.out.println("用户不存在。");
                return;
            }

            boolean isFrozen = user.isFrozen() == 1;
            String newStatus = isFrozen ? "解冻" : "冻结";

            System.out.print("确认" + newStatus + "用户 " + name + " 吗？(y/n): ");
            String confirm = scanner.nextLine().trim().toLowerCase();
            if (confirm.equals("y")) {
                user.setFrozen(isFrozen ? 0 : 1);
                userDAO.updateUser(user);
                System.out.println("用户 " + name + " 已" + newStatus + "。");
            } else {
                System.out.println("取消操作。");
            }
        } catch (SQLException e) {
            logger.error("冻结/解冻用户时出错: {}", e.getMessage());
        }
    }

    private void getUserTransactionsByUsername() {
        try {
            System.out.print("请输入用户名: ");
            String username = scanner.nextLine().trim();
            while (username.isEmpty()) {
                System.out.print("用户名不能为空，请重新输入: ");
                username = scanner.nextLine().trim();
            }

            User user = userDAO.getUsrByName(username);
            if (user == null) {
                System.out.println("用户不存在。");
                return;
            }

            List<Transaction> transactions = transactionDAO.getTransactionsByUserId(user.getId());
            if (transactions.isEmpty()) {
                System.out.println("该用户没有交易记录。");
            } else {
                System.out.println("+-----------------+----------------------+----------------------+----------------------+----------------------+");
                System.out.printf("| %-15s | %-20s | %-20s | %-20s | %-20s |\n", "TransactionType", "Amount", "Total Balance", "Transaction Date", "Description");
                System.out.println("+-----------------+----------------------+----------------------+----------------------+----------------------+");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (Transaction transaction : transactions) {
                    System.out.printf("| %-15s | %-20.2f | %-20.2f | %-20s | %-20s |\n",
                            transaction.getTransactionType(),
                            transaction.getAmount(),
                            transaction.getTotalBalance(),
                            dateFormat.format(transaction.getTransactionDate()),
                            transaction.getDescription());
                }
                System.out.println("+-----------------+----------------------+----------------------+----------------------+----------------------+");
            }
        } catch (SQLException e) {
            logger.error("查询交易记录时出错: {}", e.getMessage());
        }
    }

    private void getAllUser() {
        try {
            User[] users = userDAO.getAllUser();
            if (users.length > 0) {
                System.out.println("All user information table：");
                System.out.println("+-----------------+----------------------+----------------------+----------------------+");
                System.out.printf("| %-15s | %-20s | %-20s | %-20s |\n", "user", "pwd", "phone", "balance");
                System.out.println("+-----------------+----------------------+----------------------+----------------------+");
                for (User user : users) {
                    System.out.printf("| %-15s | %-20s | %-20s | %-20.2f |\n", user.getUsername(), user.getPassword(), user.getContactInfo(), user.getBalance());
                }
                System.out.println("+-----------------+----------------------+----------------------+----------------------+");
            } else {
                System.out.println("没有用户信息。");
            }
        } catch (SQLException e) {
            logger.error("获取用户数据时出错: {}", e.getMessage());
        }
    }

    private void deleteUser() {
        try {
            System.out.print("请输入要删除的用户名: ");
            String name = scanner.nextLine().trim();
            while (name.isEmpty()) {
                System.out.print("用户名不能为空，请重新输入: ");
                name = scanner.nextLine().trim();
            }

            User user = userDAO.getUsrByName(name);
            if (user == null) {
                System.out.println("用户不存在。");
                return;
            }

            System.out.print("确认删除用户 " + name + " 吗？(y/n): ");
            String confirm = scanner.nextLine().trim().toLowerCase();
            if (confirm.equals("y")) {
                userDAO.deleteUser(user.getUsername());
                System.out.println("用户 " + name + " 已删除。");
            } else {
                System.out.println("取消删除操作。");
            }
        } catch (SQLException e) {
            logger.error("删除用户时出错: {}", e.getMessage());
        }
    }
}